package cn.threewaters.qtyy.web.controller.sys;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;

import cn.threewaters.qtyy.common.bean.PageBean;
import cn.threewaters.qtyy.common.bean.ResponseJson;
import cn.threewaters.qtyy.config.shiro.EncryptPwd;
import cn.threewaters.qtyy.dit.one.entity.SysRole;
import cn.threewaters.qtyy.dit.one.entity.SysUser;
import cn.threewaters.qtyy.dit.one.entity.SysUserRole;
import cn.threewaters.qtyy.dit.one.entity.base.OneBaseModel;
import cn.threewaters.qtyy.service.sys.SysRoleService;
import cn.threewaters.qtyy.service.sys.SysUserRoleService;
import cn.threewaters.qtyy.service.sys.SysUserService;
import cn.threewaters.qtyy.util.hutool.core.util.ObjectUtil;
import cn.threewaters.qtyy.util.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

@Api(tags = "用户管理")
@Controller
@RequestMapping(value = "/sysUser")
public class SysUserController {

	@Resource
	private SysUserService sysUserService;

	@Resource
	private SysRoleService sysRoleService;

	@Resource
	private SysUserRoleService sysUserRoleService;

	/**
	 * 用户管理主页面
	 * 
	 * @return
	 */
	@ApiIgnore
	@ApiOperation(value = "用户管理主页面")
	@RequestMapping(value = "/main", method = RequestMethod.GET)
	public ModelAndView sysUserMain() {
		return new ModelAndView("system/sys_user/sys_user_main");
	}

	@ApiIgnore
	@ApiOperation(value = "用户新增页面")
	@RequestMapping(value = "/add/view", method = RequestMethod.GET)
	public ModelAndView sysUserAddView(ModelMap modelMap) {
		List<SysRole> sysRoles = sysRoleService
				.selectList(new EntityWrapper<SysRole>().eq("active_flag", OneBaseModel.ACTIVE_FLAG_YES));
		modelMap.addAttribute("sysRoles", sysRoles);
		return new ModelAndView("system/sys_user/sys_user_add");
	}

	@ApiIgnore
	@ApiOperation(value = "用户信息修改页面")
	@RequestMapping(value = "/update/view/{userId}", method = RequestMethod.GET)
	public ModelAndView sysUserUpdateView(@PathVariable(value = "userId") String userId, String operator,
			ModelMap modelMap) throws Exception {
		List<SysRole> sysRoles = sysRoleService
				.selectList(new EntityWrapper<SysRole>().eq("active_flag", OneBaseModel.ACTIVE_FLAG_YES));
		modelMap.addAttribute("sysRoles", sysRoles);

		SysUser sysUser = sysUserService.selectById(userId);

		List<SysUserRole> sysUserRoleList = sysUserRoleService.selectList(
				new EntityWrapper<SysUserRole>().eq("active_flag", OneBaseModel.ACTIVE_FLAG_YES).eq("user_id", userId));
		List<String> roles = Lists.newArrayList();
		for (SysUserRole sysUserRole : sysUserRoleList) {
			roles.add(sysUserRole.getRoleId());
		}
		sysUser.setRoles(roles);

		if (StrUtil.isNotEmpty(operator) && ObjectUtil.isNotNull(sysUser)) {
			modelMap.put("operator", operator);
			modelMap.put("sysUser", sysUser);
			return new ModelAndView("system/sys_user/sys_user_update", modelMap);
		} else {
			modelMap.put("status", 500);
			modelMap.put("error", "请填写准确的参数!");
			return new ModelAndView("greeting", modelMap);
		}
	}

	@ApiOperation(value = "分页查询用户集合")
	@ApiImplicitParams({ @ApiImplicitParam(name = "pageBean", value = "分页对象", required = true, dataType = "PageBean"),
			@ApiImplicitParam(name = "sysUser", value = "用户对象", required = true, dataType = "SysUser") })
	@RequestMapping(value = "/page/list", method = RequestMethod.GET)
	@ResponseBody
	public ResponseJson getSysUserPageList(PageBean pageBean, SysUser sysUser) throws Exception {
		Page<SysUser> sysUsers = sysUserService.selectPage(
				new Page<SysUser>(pageBean.getPageNumber(), pageBean.getPageSize()),
				new EntityWrapper<SysUser>(sysUser));
		return ResponseJson.builder().success(true).obj(sysUsers).build();
	}

	@ApiOperation(value = "增加用户")
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public ResponseJson sysUserAdd(@ApiParam SysUser sysUser) throws Exception {
		new EncryptPwd().encryptPassword(sysUser);
		sysUserService.insertSysUser(sysUser);
		return ResponseJson.builder().success(true).msg("保存成功").build();
	}

	@ApiOperation(value = "修改用户")
	@ApiImplicitParams({ @ApiImplicitParam(name = "sysUser", value = "用户对象", required = true, dataType = "SysUser") })
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public ResponseJson sysUserUpdate(SysUser sysUser) throws Exception {
		if (StrUtil.isNotEmpty(sysUser.getPassword())) {// 修改了密码
			if (sysUser.getUsername().equalsIgnoreCase("admin")) {
				return ResponseJson.builder().msg("请不要修改管理员的密码").build();
			}
			new EncryptPwd().encryptPassword(sysUser);
		}
		sysUserService.updateSysUser(sysUser);
		return ResponseJson.builder().success(true).msg("更新成功").build();
	}

	@ApiOperation(value = "批量删除用户")
	@ApiImplicitParams({ @ApiImplicitParam(name = "idList", value = "用户ID数组", required = true, dataType = "Array") })
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public ResponseJson deleteSysUsers(@RequestBody List<String> idList) throws Exception {
		boolean isSuccess = sysUserService.deleteBatchIds(idList);
		isSuccess = sysUserRoleService.delete(new EntityWrapper<SysUserRole>().in("user_id", idList));
		return ResponseJson.builder().success(isSuccess).msg("删除成功").build();
	}

	@ApiOperation(value = "验证登录账号是否唯一")
	@ApiImplicitParams({ @ApiImplicitParam(name = "username", value = "登录账号", required = true, dataType = "String") })
	@RequestMapping(value = "/uniqueness/username", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Boolean> checkUsername(String username) {
		boolean exitLoginName = sysUserService.isExitLoginName(username);
		ImmutableMap<String, Boolean> immutableMap = null;
		if (exitLoginName) {
			immutableMap = ImmutableMap.of("valid", true);
		} else {
			immutableMap = ImmutableMap.of("valid", false);
		}
		return immutableMap;
	}

}
